"""
审计日志中间件
"""
from django.utils.deprecation import MiddlewareMixin
from django.contrib.auth.models import AnonymousUser
from .models import AuditLog
from accounts.utils import get_client_ip, get_user_agent


class AuditLogMiddleware(MiddlewareMixin):
    """审计日志中间件"""
    
    def process_request(self, request):
        """处理请求"""
        # 存储请求信息到request对象中，供后续使用
        request.audit_info = {
            'ip_address': get_client_ip(request),
            'user_agent': get_user_agent(request),
            'request_path': request.path,
            'request_method': request.method,
        }
        return None
    
    def process_response(self, request, response):
        """处理响应"""
        # 这里可以记录一些通用的审计日志
        # 具体的业务日志在各个视图中记录
        return response
    
    @staticmethod
    def log_action(request, action, message, **kwargs):
        """记录操作日志"""
        user = request.user if hasattr(request, 'user') and not isinstance(request.user, AnonymousUser) else None
        audit_info = getattr(request, 'audit_info', {})
        
        return AuditLog.objects.create(
            user=user,
            action=action,
            message=message,
            ip_address=audit_info.get('ip_address'),
            user_agent=audit_info.get('user_agent'),
            request_path=audit_info.get('request_path'),
            request_method=audit_info.get('request_method'),
            **kwargs
        )
